import { deleteArticle, queryArticleList } from '@/service/article-column';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { history, useModel } from '@umijs/max';
import { App, Button, message } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { defaultColumns } from './components/columns';

const ArticleList: React.FC = () => {
  const { modal } = App.useApp();
  const actionRef = useRef<ActionType>();
  const [columns, setColumns] = useState<ProColumns<API.RuleListItem>[]>([]);
  const { initialState } = useModel('@@initialState');
  const currentUser = initialState?.currentUser || {};

  const goToArticleDetail = (id) => {
    history.push(id ? `/article/detail/${id}` : '/article/detail');
  };

  // 删除文章
  const deleteArticleById = (id) => {
    modal.confirm({
      title: '删除提示',
      content: `确定删除id为${id}的文章吗`,
      onOk: async () => {
        const res = await deleteArticle(id);
        if (res) {
          message.success('操作成功');
          actionRef?.current?.reloadAndRest();
        }
      },
    });
  };

  useEffect(() => {
    // 访客不展示操作按钮
    if (currentUser.roleWeight === 3) {
      defaultColumns.pop();
    } else {
      defaultColumns[defaultColumns.length - 1].render = (text, item) => {
        return (
          <>
            <Button type="link" onClick={() => goToArticleDetail(item.id)}>
              编辑
            </Button>
            <Button type="link" onClick={() => deleteArticleById(item.id)}>
              删除
            </Button>
          </>
        );
      };
    }

    setColumns(defaultColumns);
  }, []);

  // 表格查询
  const tableSearch = async (params) => {
    let values = {
      ...params,
      pageNum: params.current,
      pageSize: params.pageSize,
    };
    delete values.current;

    const res = await queryArticleList(values);

    return { success: true, data: res?.list || [], total: res?.total || 0 };
  };

  return (
    <PageContainer>
      <ProTable
        actionRef={actionRef}
        rowKey={(item) => item.id}
        request={tableSearch}
        columns={columns}
        defaultSize="small"
        search={{
          labelWidth: 'auto',
          defaultCollapsed: false,
        }}
        toolBarRender={() =>
          currentUser?.roleWeight < 3
            ? [
                <Button key="add" type="primary" onClick={() => goToArticleDetail()}>
                  新建文章
                </Button>,
              ]
            : null
        }
        scroll={{ x: 'max-content' }}
      />
    </PageContainer>
  );
};

export default ArticleList;
